{
 "cells": [
  {
   "source": [
    "## 面向过程编程  \n",
    "编程主要用到的是“函数”知识，将每个过程步骤打包成函数，再依次调用  \n",
    "## 面向对象编程  \n",
    "编程主要用到的是“类和对象”知识  \n",
    "生活的实例 >> 抽象为类 >> 程序开发中的对象,继承类的特征  "
   ],
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": [
       "['__annotations__',\n",
       " '__call__',\n",
       " '__class__',\n",
       " '__closure__',\n",
       " '__code__',\n",
       " '__defaults__',\n",
       " '__delattr__',\n",
       " '__dict__',\n",
       " '__dir__',\n",
       " '__doc__',\n",
       " '__eq__',\n",
       " '__format__',\n",
       " '__ge__',\n",
       " '__get__',\n",
       " '__getattribute__',\n",
       " '__globals__',\n",
       " '__gt__',\n",
       " '__hash__',\n",
       " '__init__',\n",
       " '__init_subclass__',\n",
       " '__kwdefaults__',\n",
       " '__le__',\n",
       " '__lt__',\n",
       " '__module__',\n",
       " '__name__',\n",
       " '__ne__',\n",
       " '__new__',\n",
       " '__qualname__',\n",
       " '__reduce__',\n",
       " '__reduce_ex__',\n",
       " '__repr__',\n",
       " '__setattr__',\n",
       " '__sizeof__',\n",
       " '__str__',\n",
       " '__subclasshook__']"
      ]
     },
     "metadata": {},
     "execution_count": 3
    }
   ],
   "source": [
    "# 查看某个函数的所有方法\n",
    "import pandas as pd\n",
    "dir(pd.DataFrame.groupby)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "报道！我是类ClassName的一个方法！\n“50”是类ClassName的一个属性！\n"
     ]
    }
   ],
   "source": [
    "### 类：函数包，可以放置函数和变量，然后类中的函数可以很方便的使用类中的变量\n",
    "# 语法：创建一个名为“ClassName”的类，类名一般首字母要大写，(): 不能丢   \n",
    "class ClassName():\n",
    "    var = 100          # 定义类中的变量，被称为类的【属性】\n",
    "    def function():    # 定义类中的函数，被称为类的【方法】\n",
    "        print('报道！我是类ClassName的一个方法！')\n",
    "ClassName.var = 50      \n",
    "ClassName.function()\n",
    "print('“%s”是类ClassName的一个属性！'% ClassName.var)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class robot():    #一般类名称为操作对象，首字母最好大写！\n",
    "    IQ = 200\n",
    "    # 以上为类属性\n",
    "\n",
    "    def greet():\n",
    "        print('主人你好！我的智商是%s' % robot.IQ) #错误用法\n",
    "    # 以上为类方法\n",
    "\n",
    "robot.greet()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class robot():\n",
    "    IQ = 200\n",
    "    # 以上为类属性\n",
    "\n",
    "    @classmethod    #允许下面函数使用类属性，不用就报错\n",
    "    #  该函数只能访问到类的属性，不能获取实例的属性  【不太理解】\n",
    "    def greet(rob):    #传输类的名称\n",
    "        print('主人你好！我的智商是%s' % rob.IQ)\n",
    "    # 以上为类方法\n",
    "\n",
    "robot.greet()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "'''【正确案例】'''\n",
    "\n",
    "class 类A():\n",
    "    变量1 = 100\n",
    "    变量2 = 200\n",
    "    \n",
    "    def 函数1():  # 【不需要】使用类属性\n",
    "        print('我不需要使用类属性。')\n",
    "    \n",
    "    @classmethod\n",
    "    def 函数2(cls):  # 【需要】使用类属性，或者为其赋值\n",
    "        print(cls.变量1)\n",
    "        print(cls.变量2)\n",
    "\n",
    "类A.函数1()\n",
    "类A.函数2()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "念给张三的诗：\n《卜算子》\n我住长江头，\n君住长江尾。\n日日思君不见君，\n共饮长江水。\n"
     ]
    }
   ],
   "source": [
    "#向类方法传递参数\n",
    "class 念诗类():\n",
    "    一首诗 = ['《卜算子》','我住长江头，','君住长江尾。','日日思君不见君，','共饮长江水。']\n",
    "    \n",
    "    @classmethod\n",
    "    def 念诗函数(cls,参数):\n",
    "        print('念给'+ 参数 +'的诗：')\n",
    "        for i in cls.一首诗:\n",
    "            print(i)\n",
    "念诗类.念诗函数('张三')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#调用其他类方法\n",
    "class 成绩单():\n",
    "    @classmethod\n",
    "    def 录入成绩单(cls):\n",
    "        cls.学生姓名 = input('请输入学生姓名：')\n",
    "        cls.语文_成绩 = int(input('请输入语文成绩：'))\n",
    "        cls.数学_成绩 = int(input('请输入数学成绩：'))\n",
    "\n",
    "    @classmethod\n",
    "    def 计算平均分(cls):\n",
    "        a = (cls.语文_成绩 + cls.数学_成绩)/2\n",
    "        return a   \n",
    "\n",
    "    @classmethod\n",
    "    def 评级(cls):\n",
    "        平均分 = cls.计算平均分() \n",
    "        if 平均分>=90:\n",
    "            print(cls.学生姓名 + '的评级是：优')\n",
    "        elif 平均分>= 80 and 平均分<90 :\n",
    "            print(cls.学生姓名 + '的评级是：良')\n",
    "        elif 平均分>= 60 and 平均分<80 :\n",
    "            print(cls.学生姓名 + '的评级是：中')\n",
    "        else:\n",
    "            print(cls.学生姓名 + '的评级是：差')\n",
    "\n",
    "成绩单.录入成绩单()\n",
    "成绩单.评级()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#作业12.1\n",
    "# 创建一个人事系统类\n",
    "class hrSystem:\n",
    "    name = ''       # 创建存储员工名字的变量 name\n",
    "    salary = 0      # 创建存储员工工资的变量 salary\n",
    "    kpi = 0         #  创建存储员工绩效的变量 kpi \n",
    "    \n",
    "    @classmethod\n",
    "    def load(cls):\n",
    "        cls.name = input('员工姓名：')\n",
    "        cls.kpi = int(input('员工绩效'))\n",
    "        if cls.check_name():\n",
    "            print('员工 %s 的绩效得分为 %d'%(cls.name,cls.kpi))\n",
    "#     @classmethod\n",
    "#     def evaluate(cls):\n",
    "#         name = hrSystem.load()[0]     ##函数被调用后会从头开始走\n",
    "#         kpi = hrSystem.load()[1]\n",
    "#         if kpi > 95 :\n",
    "#             print('恭喜%s拿到明星员工奖杯！'%name)\n",
    "#         elif kpi >= 80:\n",
    "#             print('恭喜%s拿到优秀员工奖杯！'%name)\n",
    "#         else :\n",
    "#             print('很遗憾%s这次没有评上奖杯，希望来年努力工作，勇创佳绩！'%name)\n",
    "    @classmethod\n",
    "    def evaluate(cls):\n",
    "        if doingornot :\n",
    "            name = cls.name\n",
    "            kpi = cls.kpi\n",
    "            if kpi > 95 :\n",
    "                print('恭喜%s拿到明星员工奖杯！'%name)\n",
    "            elif kpi >= 80:\n",
    "                print('恭喜%s拿到优秀员工奖杯！'%name)\n",
    "            else :\n",
    "                print('很遗憾%s这次没有评上奖杯，希望来年努力工作，勇创佳绩！'%name)\n",
    "        else:\n",
    "            pass\n",
    "\n",
    "    @classmethod\n",
    "    def check_name(cls):\n",
    "        global doingornot\n",
    "        if cls.name not in ['bob', 'candy', 'jony', 'kelly']:\n",
    "            print('录入错误！spy不是本公司员工！')\n",
    "            doingornot = 0\n",
    "        else :\n",
    "            print('录入正确')\n",
    "            doingornot = 1\n",
    "            \n",
    "hrSystem.load()\n",
    "hrSystem.evaluate()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#作业12.1\n",
    "class Calender():\n",
    "    date = '2020-08-08'\n",
    "    # 事件清单，以字典形式给出，键为事件，值是安排的时间\n",
    "    things = {'给父母买礼物':'9:00', '学习':'10:00', '和朋友聚会':'18:30'}\n",
    "    \n",
    "    @classmethod\n",
    "#     def add(cls):\n",
    "#         a = input('你要做什么事：')\n",
    "#         cls.things[a] = input('你要在什么时间做这件事：')\n",
    "    def add(cls,thing,time):   # 增加变量\n",
    "        cls.things[thing] = time\n",
    "\n",
    "    @classmethod\n",
    "    def printcalender(cls):\n",
    "        print(cls.things)\n",
    "\n",
    "    @classmethod\n",
    "    def delete(cls):\n",
    "        a = input('你想删除哪件事：')\n",
    "        del cls.things[a]\n",
    "        \n",
    "        \n",
    "Calender.printcalender()\n",
    "Calender.add('写日记','20：00')\n",
    "Calender.delete()\n",
    "Calender.printcalender()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "### 类的实例化与对象   类是【模板】，对象是【实例对象】\n",
    "\n",
    "#【直接使用】类:\n",
    "class Robot():\n",
    "    var1 = 100\n",
    "    var2 = 200\n",
    "    \n",
    "    @classmethod\n",
    "    def function(cls):\n",
    "        print(cls.var1)\n",
    "        print(cls.var2)\n",
    "\n",
    "Robot.function()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#【实例化后再使用】类:\n",
    "class Model():\n",
    "    var = 'abc'\n",
    "                            # 不需要@classmethod\n",
    "    def function(self):     # 当要调用自身属性方法时,函数第一个形参为self【共识】\n",
    "        print('已完成实例化！')\n",
    "        print('类属性的值为：'+self.var)\n",
    "        \n",
    "exp1 = Model()              # 实例化：对类进行赋值\n",
    "exp1.function()             # 实例化再使用\n",
    "\n",
    "\n",
    "## 修改实例属性\n",
    "exp1.var = 'cba'\n",
    "print(Model.var)\n",
    "print(exp1.var)\n",
    "Model.var = '修改类变量可以影响到实例变量'\n",
    "print(exp1.var)       #运行结果证明影响不了实例变量"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#修改类方法将改变实例方法    ！！！实例方法不可改写\n",
    "class 幸运():\n",
    "    def 好运翻倍(self):\n",
    "        print('好的，我把它存了起来，然后翻了888倍还给你：' + str(self.幸运数*888))\n",
    "\n",
    "def 好运翻倍2(a):    #   ！注意使用   “a.幸运数”\n",
    "    print('好的，我把它存了起来，然后翻了666倍还给你：' + str(a.幸运数*666))\n",
    "\n",
    "幸运.幸运数 = int(input('你的幸运数是多少？请输入一个整数。'))\n",
    "\n",
    "幸运.好运翻倍 = 好运翻倍2     #类方法修改\n",
    "\n",
    "实例 = 幸运()  # 实例化\n",
    "实例.好运翻倍()\n",
    "\n",
    "实例.好运翻倍 = 好运翻倍2    #！！！实例方法不可改写\n",
    "实例.好运翻倍()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "###初始化类  __init__\n",
    "class Cls():\n",
    "    def __init__(self):    #初始化函数，括号中第一个参数一定要写上self，不然会报错\n",
    "        print('实例化成功！')\n",
    "        self.donext()   #通常将打包好的执行函数放在初始化中\n",
    "        \n",
    "    def donext(self):\n",
    "        print('执行函数已调用！')\n",
    "        \n",
    "exp = Cls()       #在实例化的同时就调用了初始化函数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Multiply():\n",
    "    def __init__(self,inch):\n",
    "        self.inch = inch   # 将实例括号的参数赋值到类变量中\n",
    "\n",
    "    def prt(self):\n",
    "        for i in range(self.inch+1):\n",
    "            for x in range(1,i+1):\n",
    "                print( '%d X %d = %d' % (i ,x ,i*x) ,end = '  ' )\n",
    "            print('  ')\n",
    "\n",
    "multiply3 = Multiply(3)\n",
    "multiply3.prt()\n",
    "\n",
    "multiply5 = Multiply(5)\n",
    "multiply5.prt()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "### 类的继承\n",
    "#场景：新的类和旧类大部分相同，又有一部分不同\n",
    "#格式      class 子类(父类)：\n",
    "class father():\n",
    "    def __init__(self,x):\n",
    "        self.var = x\n",
    "    def printchara(self):\n",
    "        print('我继承了爸爸的%d亿遗产'%self.var)\n",
    "        \n",
    "class son(father):\n",
    "    pass  # pass语句代表“什么都不做”\n",
    "\n",
    "son_exp = son(2)\n",
    "son_exp.printchara()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "我是高级机器人ALPHA！智商高达150!\n"
     ]
    }
   ],
   "source": [
    "# 继承子类的修改\n",
    "class 基础机器人():\n",
    "    def __init__(self,参数):\n",
    "        self.姓名 = 参数\n",
    "\n",
    "    def 自报姓名(self):\n",
    "        print('我是' + self.姓名 + '！')     \n",
    "\n",
    "    def 卖萌(self):\n",
    "        print('主人，求抱抱！')\n",
    "\n",
    "class 高级机器人(基础机器人):\n",
    "    def __init__(self,姓名,智商):   # 子类重写了父类的方法\n",
    "        self.姓名 = 姓名\n",
    "        self.智商 = 智商\n",
    "    \n",
    "    def 自报姓名(self):         \n",
    "        print('我是高级机器人%s！智商高达%d!'%(self.姓名,self.智商))       \n",
    "\n",
    "ALPHA = 高级机器人('ALPHA',150)\n",
    "ALPHA.自报姓名()\n",
    "\n",
    "#还有多重继承\n",
    "#格式：    class 子类(父类1,父类2,……)   较复杂不实用"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#实例\n",
    "class texi():\n",
    "    def __init__(self,fee,bgkm,bgmy):\n",
    "        self.fee = fee\n",
    "        self.bgkm = bgkm\n",
    "        self.bgmy = bgmy\n",
    "\n",
    "    def account(self):\n",
    "        self.recordkm()\n",
    "        self.calcufee()\n",
    "        self.infoprint()\n",
    "    \n",
    "    def recordkm(self):\n",
    "        self.km = float(input('请输入行程公里数：'))\n",
    "\n",
    "    def calcufee(self):\n",
    "        if self.km <= self.bgkm:\n",
    "            self.cost = self.bgmy\n",
    "        else :\n",
    "            self.cost = self.bgmy + self.fee * ( self.km - self.bgkm )\n",
    "        \n",
    "    def infoprint(self):\n",
    "        print('费用一共是：' + str(self.cost) + '元')\n",
    "\n",
    "# 小王的出租车 = texi(2.5,3,15)\n",
    "# 小王的出租车.account()\n",
    "\n",
    "class elec_texi(texi):\n",
    "    def calcufee(self):\n",
    "        if self.km <= self.bgkm:\n",
    "            self.cost = self.bgmy * 0.8\n",
    "        else :\n",
    "            self.cost = (self.bgmy + self.fee * ( self.km - self.bgkm ))*0.8\n",
    "        \n",
    "小李的出租车 = elec_texi(2.5,3,15)\n",
    "小李的出租车.account()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Person():\n",
    "    def __init__(self, name):\n",
    "        self.name = name\n",
    "        print('大家注意了！')\n",
    "\n",
    "    def show(self):\n",
    "        print('一个叫“%s”的人来了。' % self.name)\n",
    "        \n",
    "class Man(Person):\n",
    "#     def __init__(self,name = '范罗苏姆'):\n",
    "#         self.name = '范罗苏姆'\n",
    "#         print('大家注意了！')\n",
    "    def __init__(self):\n",
    "        Person.__init__(self, name='范罗苏姆')  # 继承的基础上做一些改变\n",
    "        # 上面的括号里也可以写成(self,'范罗苏姆')，但加上参数后清晰一些，代码看起来更清晰。\n",
    "\n",
    "    def show(self):\n",
    "        print('一个叫“%s”的男人来了。' % self.name)\n",
    "\n",
    "    def leave(self):\n",
    "        print('那个叫“%s”的男人留下了他的背影。' % self.name)\n",
    "\n",
    "\n",
    "author1 = Person\n",
    "\n",
    "\n",
    "author1 = Person('吉多')\n",
    "author1.show()\n",
    "author2 = Man()\n",
    "author2.show()\n",
    "author3 = Man()\n",
    "author3.leave()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 14 实操项目\n",
    "\n",
    "def game():\n",
    "    # 从角色池各生成一个角色，随机生成属性\n",
    "    # 玩家选择角色出场顺序，打印出来\n",
    "    # 根据出场顺序判断克制关系，修改属性产生对话\n",
    "    # 三轮对决，输出战果"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 【转化为类代码】\n",
    "import time,random\n",
    "\n",
    "# 将变量放在类里面，作为类属性\n",
    "class Game():\n",
    "    player_list =  ['【狂血战士】','【森林箭手】','【光明骑士】','【独行剑客】','【格斗大师】','【枪弹专家】']\n",
    "    enemy_list = ['【暗黑战士】','【黑暗弩手】','【暗夜骑士】','【嗜血刀客】','【首席刺客】','【陷阱之王】']\n",
    "    player_info = {}\n",
    "    enemy_info = {}\n",
    "\n",
    "    # 初始化函数\n",
    "    def __init__(self):\n",
    "        # 随机抽取3个角色名形成玩家角色列表和敌人角色列表\n",
    "        self.players = random.sample(self.player_list,3)  \n",
    "        self.enemies = random.sample(self.enemy_list,3)\n",
    "        # 然后执行游戏流程的相关函数\n",
    "        self.show_role()\n",
    "        self.order_role()\n",
    "        self.pk_role()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#生成随机角色并展示\n",
    "import random\n",
    "import time\n",
    "\n",
    "# 创建一个类，可实例化成具体的游戏角色\n",
    "class Role():\n",
    "    def __init__(self, name='【角色】'):  # 把角色名作为默认参数\n",
    "        self.name = name\n",
    "        self.life = random.randint(100,150)\n",
    "        self.attack = random.randint(30,50)\n",
    "\n",
    "# 创建三个子类，可实例化为3个不同类型的角色\n",
    "class Knight(Role):\n",
    "    def __init__(self, name='【圣光骑士】'):   # 把子类角色名作为默认参数\n",
    "        Role.__init__(self,name)  # 利用了父类的初始化函数\n",
    "        self.life = self.life*5  # 骑士有5份血量\n",
    "        self.attack = self.attack*3    # 骑士有3份攻击力\n",
    "\n",
    "class Assassin(Role):\n",
    "    def __init__(self, name='【暗影刺客】'):\n",
    "        Role.__init__(self,name)\n",
    "        self.life = self.life*3\n",
    "        self.attack = self.attack*5\n",
    "\n",
    "class Bowman(Role):\n",
    "    def __init__(self, name='【精灵弩手】'):\n",
    "        Role.__init__(self,name)\n",
    "        self.life = self.life*4\n",
    "        self.attack = self.attack*4\n",
    "        \n",
    "# 创建一个类，可生成3V3并展示：可分为：欢迎语→随机生成→展示角色\n",
    "class Game:\n",
    "    def __init__(self):\n",
    "        # 初始化各种变量\n",
    "        self.players = []\n",
    "        self.enemies = []\n",
    "        self.score = 0\n",
    "        # 执行各种游戏函数\n",
    "        self.game_start()\n",
    "        self.born_role()\n",
    "#         print(self.enemies)\n",
    "        self.show_role()\n",
    "\n",
    "\n",
    "    # 欢迎语\n",
    "    def game_start(self):\n",
    "        print('------------ 欢迎来到“PK小游戏” ------------')\n",
    "        print('将自动生成【玩家角色】和【电脑人物】')\n",
    "        input('请按回车键继续。')\n",
    "    \n",
    "    # 随机生成6个角色\n",
    "    def born_role(self):\n",
    "        for i in range(3):\n",
    "            self.players.append(random.choice([Knight(),Assassin(),Bowman()]))\n",
    "            self.enemies.append(random.choice([Knight(),Assassin(),Bowman()]))\n",
    "#     def born_role(self):\n",
    "#         a = Knight()\n",
    "#         b = Assassin()\n",
    "#         c = Bowman()\n",
    "#         list1 = [a,b,c]\n",
    "#         for i in range(3):\n",
    "#             fighternum = random.randint(0,2)\n",
    "#             self.players.append(list1[fighternum])\n",
    "            \n",
    "#         for i in range(3):\n",
    "#             fighternum = random.randint(0,2)\n",
    "#             self.enemies.append(list1[fighternum])\n",
    "\n",
    "    # 展示角色\n",
    "    def show_role(self):\n",
    "        print('----------------- 角色信息 -----------------')\n",
    "        print('你的队伍：')\n",
    "        for i in range(3):\n",
    "            print( '『我方』%s 血量：%s  攻击：%s'%\n",
    "            (self.players[i].name,self.players[i].life,self.players[i].attack))\n",
    "        print('--------------------------------------------')\n",
    "\n",
    "        print('敌人队伍：')\n",
    "        for i in range(3):\n",
    "            print('『敌方』%s 血量：%s  攻击：%s'%\n",
    "            (self.enemies[i].name,self.enemies[i].life,self.enemies[i].attack))\n",
    "        print('--------------------------------------------')\n",
    "\n",
    "\n",
    "gp = Game()  # 运行游戏"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "    # 角色排序，选择出场顺序       \n",
    "    def order_role(self):  # 在类方法中加入self作为参数\n",
    "        order_dict = {}\n",
    "        for i in range(3):\n",
    "            order = int(input('你想将 %s 放在第几个上场？(输入数字1~3)'% self.players[i]))\n",
    "            order_dict[order] = self.players[i]  \n",
    "\n",
    "        self.players = []  # 变量前加上self.其余几处同理\n",
    "        for i in range(1,4):\n",
    "            self.players.append(order_dict[i]) \n",
    "\n",
    "        print('\\n我方角色的出场顺序是：%s、%s、%s' %(self.players[0],self.players[1],self.players[2]))\n",
    "        print('敌方角色的出场顺序是：%s、%s、%s' %(self.enemies[0],self.enemies[1],self.enemies[2]))   "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 属性克制\n",
    "    def fight_buff(self, opponent):  # fight_buff的意思是“战斗强化”，opponent的意思是“对手”\n",
    "        if opponent.name  == '老鼠':\n",
    "            self.attack = int(self.attack * 1.5)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "------------ 欢迎来到“炼狱角斗场” ------------\n",
      "在昔日的黄昏山脉，奥卢帝国的北境边界上，有传说中的“炼狱角斗场”。\n",
      "鲜血与战斗是角斗士的归宿，金钱与荣耀是角斗士的信仰！\n",
      "今日，只要你【你的队伍】能取得胜利，你将获得一笔够花500年的财富。\n",
      "将随机生成【你的队伍】和【敌人队伍】！\n",
      "我们不都一样\n",
      "对手不都一样\n",
      "----------------- 角色信息 -----------------\n",
      "你的队伍：\n",
      "『我方』【圣光骑士】 血量：750.0  攻击：141\n",
      "『我方』【精灵弩手】 血量：404  攻击：148\n",
      "『我方』【圣光骑士】 血量：700.0  攻击：141\n",
      "--------------------------------------------\n",
      "敌人队伍：\n",
      "『敌方』【圣光骑士】 血量：695  攻击：144\n",
      "『敌方』【暗影刺客】 血量：401.25  攻击：220\n",
      "『敌方』【暗影刺客】 血量：502.5  攻击：240\n",
      "--------------------------------------------\n",
      "输入正确！\n",
      "\n",
      "你的队伍出场顺序是：【圣光骑士】、【精灵弩手】、【圣光骑士】\n",
      "敌人队伍出场顺序是：【圣光骑士】、【暗影刺客】、【暗影刺客】\n",
      "\n",
      "----------------- 【第1轮】 -----------------\n",
      "--------------------------------------------\n",
      "我方【圣光骑士】 发起了攻击，敌方【圣光骑士】 剩余血量 554\n",
      "敌方【圣光骑士】 发起了攻击，我方【圣光骑士】 剩余血量 606.0\n",
      "--------------------------------------------\n",
      "我方【圣光骑士】 发起了攻击，敌方【圣光骑士】 剩余血量 413\n",
      "敌方【圣光骑士】 发起了攻击，我方【圣光骑士】 剩余血量 462.0\n",
      "--------------------------------------------\n",
      "我方【圣光骑士】 发起了攻击，敌方【圣光骑士】 剩余血量 272\n",
      "敌方【圣光骑士】 发起了攻击，我方【圣光骑士】 剩余血量 318.0\n",
      "--------------------------------------------\n",
      "我方【圣光骑士】 发起了攻击，敌方【圣光骑士】 剩余血量 131\n",
      "敌方【圣光骑士】 发起了攻击，我方【圣光骑士】 剩余血量 174.0\n",
      "--------------------------------------------\n",
      "我方【圣光骑士】 发起了攻击，敌方【圣光骑士】 剩余血量 -10\n",
      "敌方【圣光骑士】 发起了攻击，我方【圣光骑士】 剩余血量 30.0\n",
      "--------------------------------------------\n",
      "\n",
      "恭喜，我方【圣光骑士】 活下来了。\n",
      "\n",
      "----------------- 【第2轮】 -----------------\n",
      "『敌方』【暗影刺客】对 『我方』【精灵弩手】说：“主动找死，就别怪我心狠手辣。”\n",
      "--------------------------------------------\n",
      "我方【精灵弩手】 发起了攻击，敌方【暗影刺客】 剩余血量 253.25\n",
      "敌方【暗影刺客】 发起了攻击，我方【精灵弩手】 剩余血量 74\n",
      "--------------------------------------------\n",
      "我方【精灵弩手】 发起了攻击，敌方【暗影刺客】 剩余血量 105.25\n",
      "敌方【暗影刺客】 发起了攻击，我方【精灵弩手】 剩余血量 -256\n",
      "--------------------------------------------\n",
      "\n",
      "很遗憾，我方【精灵弩手】 挂掉了！\n",
      "\n",
      "----------------- 【第3轮】 -----------------\n",
      "『我方』【圣光骑士】对 『敌方』【暗影刺客】说：“让无尽光芒制裁你的堕落！”\n",
      "--------------------------------------------\n",
      "我方【圣光骑士】 发起了攻击，敌方【暗影刺客】 剩余血量 291.5\n",
      "敌方【暗影刺客】 发起了攻击，我方【圣光骑士】 剩余血量 460.0\n",
      "--------------------------------------------\n",
      "我方【圣光骑士】 发起了攻击，敌方【暗影刺客】 剩余血量 80.5\n",
      "敌方【暗影刺客】 发起了攻击，我方【圣光骑士】 剩余血量 220.0\n",
      "--------------------------------------------\n",
      "我方【圣光骑士】 发起了攻击，敌方【暗影刺客】 剩余血量 -130.5\n",
      "敌方【暗影刺客】 发起了攻击，我方【圣光骑士】 剩余血量 -20.0\n",
      "--------------------------------------------\n",
      "\n",
      "我的天，他们俩都死了啊！\n",
      "【最终结果】\n",
      "你没有胜利，但也没有失败，在夜色中灰溜溜离开了奥卢帝国。\n"
     ]
    }
   ],
   "source": [
    "### 最后代码\n",
    "import random\n",
    "import time\n",
    "\n",
    "# 创建一个类，可实例化成具体的游戏角色\n",
    "class Role:\n",
    "    def __init__(self, name='【角色】'):  # 把角色名作为默认参数\n",
    "        self.name = name\n",
    "        self.life = random.randint(100,150)\n",
    "        self.attack = random.randint(30,50)\n",
    "\n",
    "# 创建3个子类，可实例化为3个不同的职业\n",
    "\n",
    "class Knight(Role):\n",
    "    def __init__(self, name='【圣光骑士】'):   # 把子类角色名作为默认参数\n",
    "        Role.__init__(self,name)  # 利用了父类的初始化函数\n",
    "        self.life = self.life*5  # 骑士有5份血量\n",
    "        self.attack = self.attack*3    # 骑士有3份攻击力\n",
    "\n",
    "    # 职业克制关系\n",
    "    def fight_buff(self, opponent,str1,str2):\n",
    "        if opponent.name  == '【暗影刺客】':\n",
    "            self.attack = int(self.attack * 1.5)\n",
    "            print('『%s』【圣光骑士】对 『%s』【暗影刺客】说：“让无尽光芒制裁你的堕落！”'%(str1, str2))\n",
    "\n",
    "class Assassin(Role):\n",
    "    def __init__(self, name='【暗影刺客】'):\n",
    "        Role.__init__(self,name)\n",
    "        self.life = self.life*3\n",
    "        self.attack = self.attack*5\n",
    "\n",
    "    # 职业克制关系\n",
    "    def fight_buff(self, opponent,str1,str2):\n",
    "        if opponent.name  == '【精灵弩手】':\n",
    "            self.attack = int(self.attack * 1.5)\n",
    "            print('『%s』【暗影刺客】对 『%s』【精灵弩手】说：“主动找死，就别怪我心狠手辣。”'%(str1, str2)) \n",
    "\n",
    "class Bowman(Role):\n",
    "    def __init__(self, name='【精灵弩手】'):\n",
    "        Role.__init__(self,name)\n",
    "        self.life = self.life*4\n",
    "        self.attack = self.attack*4\n",
    "\n",
    "    # 职业克制关系\n",
    "    def fight_buff(self, opponent,str1,str2):\n",
    "        if opponent.name  == '【圣光骑士】':\n",
    "            self.attack = int(self.attack * 1.5)\n",
    "            print('『%s』【精灵弩手】对 『%s』【圣光骑士】说：“骑着倔驴又如何？你都碰不到我衣服。”'%(str1, str2))\n",
    "\n",
    "# 创建一个类，可生成3V3并展示：可分为：欢迎语→随机生成→展示角色\n",
    "class Game():\n",
    "    def __init__(self):\n",
    "        self.players = []  # 存玩家顺序\n",
    "        self.enemies = []  # 存敌人顺序\n",
    "        self.score = 0  # 比赛积分\n",
    "        self.i = 0  # 记轮次\n",
    "        # 依次执行以下函数\n",
    "        self.game_start()  # 欢迎语\n",
    "        self.born_role()  # 随机生成6个角色\n",
    "        self.cooperat_role()   # 角色类型的配合合作\n",
    "        self.show_role()  # 展示角色\n",
    "        self.order_role()  # 排序并展示\n",
    "        self.pk_role()  # 让双方 Pk 并展示结果\n",
    "        self.show_result()  # 展示最终结局\n",
    "\n",
    "    # 欢迎语\n",
    "    def game_start(self):\n",
    "        print('------------ 欢迎来到“炼狱角斗场” ------------')\n",
    "        print('在昔日的黄昏山脉，奥卢帝国的北境边界上，有传说中的“炼狱角斗场”。')\n",
    "        print('鲜血与战斗是角斗士的归宿，金钱与荣耀是角斗士的信仰！')\n",
    "        print('今日，只要你【你的队伍】能取得胜利，你将获得一笔够花500年的财富。')\n",
    "        time.sleep(2)\n",
    "        print('将随机生成【你的队伍】和【敌人队伍】！')\n",
    "    \n",
    "    # 随机生成6个角色\n",
    "    def born_role(self):\n",
    "        for i in range(3):\n",
    "            self.players.append(random.choice([Knight(),Assassin(),Bowman()]))\n",
    "            self.enemies.append(random.choice([Knight(),Assassin(),Bowman()]))\n",
    "            #print([Knight(),Assassin(),Bowman()]) self.players保存的为函数位置\n",
    "\n",
    "            ##尝试\n",
    "    def check(self,arr,rival):\n",
    "        tempList = []\n",
    "        for i in range(3):\n",
    "            tempList.append(arr[i].name)     #存入名字\n",
    "        tempSet = set(tempList)\n",
    "#         print(tempSet)\n",
    "        if len(tempSet) == 1:\n",
    "            print('%s都一样'% rival)\n",
    "            for i in range(3):            \n",
    "                arr[i].life = arr[i].life * 1.25\n",
    "        elif len(tempSet) == 3:\n",
    "            print('%s都不一样'% rival)\n",
    "            for i in range(3):\n",
    "                arr[i].attack = arr[i].attack * 1.25\n",
    "        else:\n",
    "            print('%s不都一样'% rival)\n",
    "            for i in range(3):\n",
    "                if (tempList[2-i] != tempList[1-i]) and (tempList[2-i] != tempList[-i]):\n",
    "                    arr[1-i].life = arr[1-i].life * 1.25\n",
    "                    arr[-i].life = arr[-i].life * 1.25\n",
    "                    \n",
    "    def cooperat_role(self):\n",
    "        self.check(self.players,'我们')            ##  玩家\n",
    "        self.check(self.enemies,'对手')\n",
    "\n",
    "\n",
    "#     def cooperat_role(self):\n",
    "#         copnum1 = 0\n",
    "#         copnum2 = 0\n",
    "#         cop1 = 0\n",
    "#         cop2 = 0\n",
    "#         for i in range(2):\n",
    "#             for j in range(i+1,3):\n",
    "#                 if self.players[i].name == self.players[j].name :\n",
    "#                     copnum1 = i\n",
    "#                     cop1 = 1\n",
    "#                     self.players[i].life = self.players[i].life * 1.25    #BUG：可能被×两次的1.25\n",
    "#                     self.players[j].life = self.players[j].life * 1.25    \n",
    "#                 if self.enemies[i].name == self.enemies[j].name :\n",
    "#                     copnum2 = i\n",
    "#                     cop2 = 1\n",
    "#                     self.enemies[i].life = self.enemies[i].life * 1.25  \n",
    "#         if(cop1):\n",
    "#             print('我们都一样,抱团起来，血量增加25%')\n",
    "#             pass\n",
    "#         else:\n",
    "#             print('我们都不一样：互相配合，攻击增加25%')\n",
    "#             for i in range(3):\n",
    "#                 self.players[i].attack = self.players[i].attack * 1.25\n",
    "#         if(cop2):\n",
    "# #             print('敌人都一样：%s抱团起来，血量增加25%' % self.enemies[copnum2].name)\n",
    "#             pass\n",
    "#         else:\n",
    "#             print('敌人都不一样：互相配合，攻击增加25%')\n",
    "#             for i in range(3):\n",
    "#                 self.enemies[i].attack = self.enemies[i].attack * 1.25\n",
    "    \n",
    "    # 展示角色\n",
    "    def show_role(self):\n",
    "        print('----------------- 角色信息 -----------------')\n",
    "        print('你的队伍：')\n",
    "        for i in range(3):\n",
    "            print( '『我方』%s 血量：%s  攻击：%s'%\n",
    "            (self.players[i].name,self.players[i].life,self.players[i].attack))\n",
    "        print('--------------------------------------------')\n",
    "\n",
    "        print('敌人队伍：')\n",
    "        for i in range(3):\n",
    "            print('『敌方』%s 血量：%s  攻击：%s'%\n",
    "            (self.enemies[i].name,self.enemies[i].life,self.enemies[i].attack))\n",
    "        print('--------------------------------------------')\n",
    "\n",
    "    # 排序并展示\n",
    "    def order_role(self):\n",
    "        \n",
    "        pre_order = [1,2,3]\n",
    "        order = []\n",
    "        while True:\n",
    "            retA = list(set(pre_order).difference(set(order)))\n",
    "\n",
    "            if retA :      #当列表差不为零时\n",
    "                try:\n",
    "                    order = []\n",
    "                    order_dict = {}\n",
    "                    left_order = [1,2,3]\n",
    "                    for i in range(3):\n",
    "                        order.append( int(input('你想将 %s 放在第几个上场？(输入数字%s)'% (self.players[i].name,left_order))))\n",
    "                        left_order.remove(order[i])\n",
    "                        order_dict[order[i]] = self.players[i]\n",
    "                except ValueError :\n",
    "                    print ('只能输入不重复的【1，2，3】三个数字')\n",
    "                    continue\n",
    "            else :         #当列表内的元素完全相同时\n",
    "                print('输入正确！')\n",
    "                break\n",
    "            \n",
    "        self.players = []\n",
    "        for i in range(1,4):\n",
    "            self.players.append(order_dict[i]) \n",
    "        print('\\n你的队伍出场顺序是：%s、%s、%s'\n",
    "        %(self.players[0].name,self.players[1].name,self.players[2].name))\n",
    "        print('敌人队伍出场顺序是：%s、%s、%s'\n",
    "        %(self.enemies[0].name,self.enemies[1].name,self.enemies[2].name))\n",
    "\n",
    "\n",
    "    # 让双方 Pk 并展示结果\n",
    "    def pk_role(self):\n",
    "        for i in range(3):\n",
    "            print('\\n----------------- 【第%s轮】 -----------------' % (i+1))\n",
    "            # 每一局开战前加buff\n",
    "            self.players[i].fight_buff(self.enemies[i],'我方','敌方')\n",
    "            self.enemies[i].fight_buff(self.players[i],'敌方','我方')\n",
    "            input('\\n战斗双方准备完毕，请按回车键继续。')\n",
    "            print('--------------------------------------------')\n",
    "    \n",
    "            while self.players[i].life >0 and self.enemies[i].life>0:\n",
    "                self.enemies[i].life -= self.players[i].attack\n",
    "                self.players[i].life -= self.enemies[i].attack\n",
    "                print('我方%s 发起了攻击，敌方%s 剩余血量 %s'%\n",
    "                (self.players[i].name,self.enemies[i].name,self.enemies[i].life))\n",
    "                print('敌方%s 发起了攻击，我方%s 剩余血量 %s'%\n",
    "                (self.enemies[i].name,self.players[i].name,self.players[i].life))\n",
    "                print('--------------------------------------------')\n",
    "                time.sleep(1)\n",
    "            if self.players[i].life <= 0 and self.enemies[i].life> 0:\n",
    "                print('\\n很遗憾，我方%s 挂掉了！'% (self.players[i].name))\n",
    "                self.score -= 1\n",
    "            elif self.players[i].life >0 and self.enemies[i].life<= 0: \n",
    "                print('\\n恭喜，我方%s 活下来了。'% (self.players[i].name))\n",
    "                self.score += 1\n",
    "            else:\n",
    "                print('\\n我的天，他们俩都死了啊！')\n",
    "\n",
    "    # 展示最终结局\n",
    "    def show_result(self):\n",
    "        input('\\n请按回车查看最终结果。\\n')\n",
    "        if self.score >0:\n",
    "            print('【最终结果】\\n你赢了，最终的财宝都归你了！')\n",
    "        elif self.score == 0:\n",
    "            print('【最终结果】\\n你没有胜利，但也没有失败，在夜色中灰溜溜离开了奥卢帝国。')\n",
    "        else:\n",
    "            print('【最终结果】\\n你输了。炼狱角斗场又多了几具枯骨。')\n",
    "\n",
    "game = Game()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "players = ['西红柿炒蛋','红烧猪蹄','爆香鸡米花']\n",
    "pre_order = [1,2,3]\n",
    "left_order = [1,2,3]\n",
    "order = []\n",
    "while True:\n",
    "    retA = list(set(pre_order).difference(set(order)))\n",
    "    \n",
    "    if retA :      #当列表差不为零时\n",
    "        try:\n",
    "            order = []\n",
    "            order_dict = {}\n",
    "            left_order = [1,2,3]\n",
    "            for i in range(3):\n",
    "                order.append( int(input('你想将 %s 放在第几个上场？(输入数字%s)'% (players[i],left_order))))\n",
    "                left_order.remove(order[i])\n",
    "                order_dict[order[i]] = players[i]\n",
    "        except ValueError :\n",
    "            print ('只能输入【1，2，3】三个数字')\n",
    "            continue\n",
    "    else :         #当列表内的元素完全相同时\n",
    "        print('输入正确！')\n",
    "        break\n",
    "\n",
    "\n",
    "print(order_dict)\n",
    "print('%s' % pre_order)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "你想将 【狂血战士】 排在第几个上场？（输入数字1-3）2\n",
      "你想将 【枪弹专家】 排在第几个上场？（输入数字1-3）3\n",
      "你想将 【光明骑士】 排在第几个上场？（输入数字1-3）1\n",
      "\n",
      "我方角色的出场顺序是：【光明骑士】 【狂血战士】 【枪弹专家】\n",
      "\n"
     ]
    }
   ],
   "source": [
    "##  最优代码\n",
    "import random\n",
    "\n",
    "player_list = ['【狂血战士】','【森林箭手】','【光明骑士】','【独行剑客】','【格斗大师】','【枪弹专家】']\n",
    "players = random.sample(player_list,3)\n",
    "order_dict = {}\n",
    "i=0\n",
    "while i < 3:\n",
    "    order = int(input('你想将 %s 排在第几个上场？（输入数字1-3）'%(players[i])))\n",
    "    if order in [1,2,3]:\n",
    "        if order in order_dict:\n",
    "            print('你输入了重复的数字，请重新输入：')\n",
    "        else:\n",
    "            order_dict[order] = players[i]\n",
    "            i += 1\n",
    "    else:\n",
    "        print('输入有误，请输入1或2或3：') # 报错2\n",
    "        \n",
    "players = []\n",
    "for i in range(1,4):\n",
    "    players.append(order_dict[i])\n",
    "print('\\n我方角色的出场顺序是：%s %s %s\\n' %(players[0],players[1],players[2]))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "name": "python3",
   "display_name": "Python 3.7.4 64-bit ('base': conda)"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  },
  "interpreter": {
   "hash": "2a7e95a32014fc1ccf24626d45a98c6e7b4373277259c22f47a91d487fc3e8a5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}